package com.example.demo.controller;

import com.example.demo.entity.*;
import com.example.demo.pojo.PlannerResult;
import com.example.demo.repository.*;
import com.example.demo.service.ActivityService;
import com.example.demo.service.HomeService;
import com.example.demo.utils.ThreadLocalUtil;
import com.example.demo.vo.Activityvo;
import com.example.demo.vo.JoinerVo;
import com.example.demo.vo.ListActivityVo;
import com.example.demo.vo.ScheduleVo;
import jakarta.validation.constraints.Null;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/activity")
public class ActivityController {

    @Autowired
    ActivityRepository activityRepository;

    @Autowired
    Act_templateRepository act_templateRepository;

    @Autowired
    ScheduleRepository scheduleRepository;

    @Autowired
    ExpenseRepository expenseRepository;

    @Autowired
    JoinerRepository joinerRepository;

    @Autowired
    ActivityService activityService;

    @Autowired
    UserRepository userRepository;


    //更新活动,service-
    @PutMapping("/update")
    public PlannerResult<String> update(@RequestBody Activityvo activityvo) {

        return activityService.update(activityvo);
    }

    //删除
    @PostMapping("/delete/{activityid}")
    public PlannerResult<String> deleteByid(@PathVariable("activityid") Integer activityid) {
        activityRepository.deleteById(activityid);
        return PlannerResult.success("删除成功");

    }

    //由id查找活动
    @GetMapping("/findactivitybyid")
    public PlannerResult<Activityvo> findActivityById(@RequestParam("activityid") Integer activityid) {

        Map<String,Object> map= ThreadLocalUtil.get();
        Integer userid=(Integer) map.get("id");

        Activity activity= activityRepository.findById(activityid).get();
        Activityvo activityvo=new Activityvo();

        BeanUtils.copyProperties(activity,activityvo);
        activityvo.setCreator(userRepository.findById(activity.getCreator_id()).get().getUsername());
        activityvo.setIs_join(false);

        joinerRepository.findByActivity_id(activityid).forEach(joiner -> {
            if (Objects.equals(joiner.getUser_id(), userid)){
                activityvo.setIs_join(true);
            }
        });

        return PlannerResult.success(activityvo);
    }


    //按页查询活动,返回Data是Page<Activity>
    @GetMapping ("/findactivitybypage")
    public PlannerResult<Page<Activity>> findActivity(@RequestParam("page") Integer page, @RequestParam("num") Integer num) {
        Pageable pageable = PageRequest.of(page, num);
        return PlannerResult.success(activityRepository.findAll(pageable));
    }

    //拿到所有模板.service
    @GetMapping("/templates")
    public PlannerResult<List<Act_template>> findtemplates() {
        return activityService.allact_template();
    }

    //选择某模板
    @GetMapping("/select_template")
    public PlannerResult<Act_template> selectActTemplateById(@RequestParam("templateid") Integer templateid) {
        return PlannerResult.success(act_templateRepository.findById(templateid).get());
    }

    //建立活动,service
    @PostMapping("/creating")
    public PlannerResult<Integer> create(@RequestBody Activityvo activityvo) {
        return activityService.create(activityvo);

    }

    //建立日程,service
    @PostMapping("/schcreating")
    public PlannerResult<String> schCreate(@RequestBody ScheduleVo scheduleVo) {
        return activityService.schCreate(scheduleVo);

    }

    //根据活动ID获取某活动的日程信息
    @GetMapping("/findschdulebyid")
    public PlannerResult<List<Schedule>> findSchduleById(@RequestParam("activityid") Integer activityid) {

        List<Schedule> s = scheduleRepository.findAllByActivity_id(activityid);
        return PlannerResult.success(s);
    }

    //修改活动状态,service
    @GetMapping("/setstate")
    public PlannerResult<String> setstate(@RequestParam("activityid") Integer activityid, @RequestParam("nextstate") String nextstate) {
        return activityService.setState(activityid, nextstate);
    }

    //活动参与者
    @GetMapping("/findmyjoiner")
    public PlannerResult<List<JoinerVo>> find_my_joiner(@RequestParam("activity_id") Integer activityid) {
        List<Joiner> listj = joinerRepository.findByActivity_id(activityid);
        List<JoinerVo> result = new ArrayList<>();

        for (Joiner join : listj) {
            JoinerVo joinerVo = new JoinerVo();
            BeanUtils.copyProperties(join,joinerVo);
            joinerVo.setUsername(userRepository.findById(join.getUser_id()).get().getUsername());
            joinerVo.setAvatar(userRepository.findById(join.getUser_id()).get().getAvatar());
            result.add(joinerVo);
        }

        System.out.println(result);
        if (!result.isEmpty()) {
            return PlannerResult.success(result);
        } else return PlannerResult.error("没有参与者");
    }

    @PutMapping("/updateJoiner")
    public PlannerResult<String> join_activity(@RequestParam("id") Integer id, @RequestParam("identity") String identity) {
        Joiner joiner = joinerRepository.findById(id).get();
        if(joiner.getId()==null){
            return PlannerResult.error("该参与者不存在");
        }
        joiner.setIdentity(identity);
        Joiner save = joinerRepository.save(joiner);
        if (save.getId()==null){
            return PlannerResult.error("更新失败");
        }else {
            return PlannerResult.success("更新成功");
        }
    }

    @PostMapping("/search")
    public PlannerResult<Page<Activity>> find_by_key(@RequestBody ListActivityVo listActivityVo )
    {
        String type = listActivityVo.getType();
        String keyword = listActivityVo.getKeyword();
        Integer page = listActivityVo.getPage();
        Integer size = listActivityVo.getSize();
        if(type.equals("name"))
        {
            Pageable pageable = PageRequest.of(page-1,size);
            Page<Activity> result = activityRepository.getByname(keyword,pageable);
            return PlannerResult.success(result);
        }
        else if (type.equals("creator_id"))
        {
            Pageable pageable = PageRequest.of(page-1,size);
            List<User> users = userRepository.findByName(keyword);
            List<Integer> ids = new ArrayList<>();
            for (User user:users
            ) {
                ids.add(user.getId());
            }
            Page<Activity> result = activityRepository.getByCreatorId(ids,pageable);
            return  PlannerResult.success(result);
        }
        else {
            Pageable pageable = PageRequest.of(page-1,size);
            Page result = activityRepository.findAll(pageable);
            return PlannerResult.success(result);
        }
    }

    @GetMapping("/userDetail")
    public PlannerResult<List<Activity>> find_by_user_id(@RequestParam("id") Integer user_id,
                                                         @RequestParam("type") String type,
                                                         @RequestParam(value = "search_key",required = false) String search_key)
    {
        Map<String,Object> map= ThreadLocalUtil.get();
        Integer userid=(Integer) map.get("id");

        if (type.equals("pub")){
            if (search_key != null)
            {
                List<Activity> result = activityRepository.getByNameLike(search_key).stream().map(activity -> {
                    if (activity.getCreator_id().equals(userid))
                    {
                        return activity;
                    }
                    else return null;
                }).collect(Collectors.toList());
                result.stream().map(activity -> {
                    activity.setJoiner_number(joinerRepository.findByActivity_id(activity.getId()).size());
                    return activity;
                }).collect(Collectors.toList());
                return PlannerResult.success(result.stream().map(activity -> {
                    activity.setJoiner_number(joinerRepository.findByActivity_id(activity.getId()).size());
                    return activity;
                }).collect(Collectors.toList()));
            }
            else {
                List<Activity> result = activityRepository.findByCreator(userid);
                return PlannerResult.success(result.stream().map(activity -> {
                    activity.setJoiner_number(joinerRepository.findByActivity_id(activity.getId()).size());
                    return activity;
                }).collect(Collectors.toList()));
            }
        }
        else if (type.equals("par")) {
            if (search_key != null)
            {
                // 获取该用户参与的所有活动ID
                List<Integer> joinedActivityIds = joinerRepository.findByUser_id(userid).stream()
                        .map(Joiner::getActivity_id)
                        .toList();

                // 根据搜索关键词查找活动，并过滤出用户已参与的活动
                return PlannerResult.success(activityRepository.getByNameLike(search_key).stream().map(activity -> {
                            if(joinedActivityIds.contains(activity.getId()))
                            {
                                return activity;
                            }
                            else return null;
                        }).collect(Collectors.toList()).stream().map(activity -> {
                    activity.setJoiner_number(joinerRepository.findByActivity_id(activity.getId()).size());
                    return activity;
                }).collect(Collectors.toList()));
            }
            else {
                List<Activity> result = joinerRepository.findByUser_idAndQuanXian(userid,"参与者").stream().map(joiner ->
                        activityRepository.findById(joiner.getActivity_id()).get()).collect(Collectors.toList());

                return PlannerResult.success(result.stream().map(activity -> {
                    activity.setJoiner_number(joinerRepository.findByActivity_id(activity.getId()).size());
                    return activity;
                }).collect(Collectors.toList()));
            }
        }else {
            return PlannerResult.error("error");
        }
    }

    @Autowired
    HomeService homeService;

    //加入
    @PostMapping("/join")
    public PlannerResult<String> join_act(@RequestBody JoinerVo joinerVo) {

        return homeService.join_act(joinerVo);
    }

    @PostMapping("/hot")
    PlannerResult<List<Activity>> hot_activity(){
        List<Activity> activities = activityRepository.findhot();
        return PlannerResult.success(activities);
    }
}
